package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Slf4j
@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    RedissonClient redissonClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        // 1.查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
        // 2 组装成父子的树形结构

        // 2.1 找到所有的一级分类
        List<CategoryEntity> level1Menus = entities.stream().filter((categoryEntity -> {
            return categoryEntity.getParentCid() == 0;
        })).map((menu) -> {
            menu.setChildren(getChildren(menu, entities));
            return menu;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());


        return level1Menus;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        // TODO 检查当前删除的菜单是否被别的地方引用

        baseMapper.deleteBatchIds(asList);
    }

    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        CategoryEntity entity = this.getById(catelogId);
        paths.add(entity.getCatId());
        if (entity.getParentCid() != 0) {
            findParentPath(entity.getParentCid(), paths);
        }
        return paths;
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);
        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[parentPath.size()]);
    }

    /**
     * 级联更新所有关联的数据
     *
     * @param category
     */
    @Override
    @Transactional
    @Caching(evict = {@CacheEvict(value = "category", key = "'getCalalogJson'"),
    @CacheEvict(value = "category", key = "'getLevel1Categorys'")})
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());

    }

    // 每一个需要缓存的数据我们都需要指定相应的名字来放入
    // name=category::getLevel1Categorys
    @Cacheable(value = {"category"}, key = "#root.method.name") // 代表当前方法的执行结果需要缓存
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
    }


    @Cacheable(value = {"category"}, key = "#root.methodName")
    public Map<String, List<Catelog2Vo>> getCalalogJson(){
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        // 1、查出所有一级分类
        List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);
        // 2、封装数据
        Map<String, List<Catelog2Vo>> parent_cid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            // 每一个一级分类，查到这个一级分类的二级分类
            List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());
            // 封装上面的结果
            List<Catelog2Vo> catelog2Vos = null;
            if (categoryEntities != null) {
                catelog2Vos = categoryEntities.stream().map(item -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, item.getCatId().toString(), item.getName());
                    // TODO 找当前二级分类的三级分类封装成vo
                    List<CategoryEntity> categoryEntityList3 = getParent_cid(selectList, item.getCatId());
                    List<Catelog2Vo.Category3Vo> category3VoList = null;
                    if (categoryEntityList3 != null) {
                        category3VoList = categoryEntityList3.stream().map(item3 -> {
                            Catelog2Vo.Category3Vo category3Vo = new Catelog2Vo.Category3Vo(catelog2Vo.getId(), item3.getCatId().toString(), item3.getName());
                            return category3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(category3VoList);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2Vos;
        }));
        return parent_cid;
    }
    // TODO 会产生堆外内存溢出，使用jedis解决
//    @Override
    public Map<String, List<Catelog2Vo>> getCalalogJsonq() {
        // TODO 空结果缓存解决缓存穿透问题
        // TODO 过期时间加一个随机值解决缓存雪崩问题
        // TODO 加锁解决缓存击穿问题
        String catelogJSON = stringRedisTemplate.opsForValue().get("catelogJSON");
        Map<String, List<Catelog2Vo>> returnValue;
        if (StringUtils.isEmpty(catelogJSON)) {
            returnValue = getCatalogJsonFromDbWithRedissonLock();
            stringRedisTemplate.opsForValue().set("catelogJSON", JSON.toJSONString(returnValue), 1, TimeUnit.DAYS);
        }
        returnValue = JSON.parseObject(catelogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
        });
        return returnValue;
    }

    // 从数据库查询并封装数据
    public Map<String, List<Catelog2Vo>> getCalalogJsonFromDBWithLocalLock() {
        // 得到锁之后应该去缓存中在确定一次
        // TODO 本地锁：在分布式情况下想要锁住所有必须使用分布式锁
        synchronized (this) {
            return getDataFromDB();
        }
    }

    // 从数据库查询并封装数据
    public Map<String, List<Catelog2Vo>> getCalalogJsonFromDBWithRedisLock() {
        String uuid = UUID.randomUUID().toString();
        Boolean lock = false;
        while (!lock) {
            lock = stringRedisTemplate.opsForValue().setIfAbsent("lock", uuid, 300, TimeUnit.SECONDS);
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        // 设置过期时间必须和加锁是同步的，原子的
//            stringRedisTemplate.expire("lock", 30, TimeUnit.SECONDS);
        // 获取到锁
        Map<String, List<Catelog2Vo>> data;
        try {
            data = getDataFromDB();
        } finally {
            String lua = "if redis.call('get',KEYS[1]) == ARGV[1]then return redis.call('del',KEYS[1]) else return 0 end";
            stringRedisTemplate.execute(new DefaultRedisScript<Integer>(lua, Integer.class),
                    Arrays.asList("lock"),
                    uuid);
        }
        // 删除锁必须也是原子的，先判断是不是本线程加的锁，使用lua脚本解锁
//            stringRedisTemplate.delete("lock");
        // 使用原子性操作进行删除锁
        return data;
    }

    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithRedissonLock() {

        //1、占分布式锁。去redis占坑
        //（锁的粒度，越细越快:具体缓存的是某个数据，11号商品） product-11-lock
        //RLock catalogJsonLock = redissonClient.getLock("catalogJson-lock");
        //创建读锁
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("catalogJson-lock");

        RLock rLock = readWriteLock.readLock();

        Map<String, List<Catelog2Vo>> dataFromDb = null;
        try {
            rLock.lock();
            //加锁成功...执行业务
            dataFromDb = getDataFromDB();
        } finally {
            rLock.unlock();
        }
        //先去redis查询下保证当前的锁是自己的
        //获取值对比，对比成功删除=原子性 lua脚本解锁
        // String lockValue = stringRedisTemplate.opsForValue().get("lock");
        // if (uuid.equals(lockValue)) {
        //     //删除我自己的锁
        //     stringRedisTemplate.delete("lock");
        // }

        return dataFromDb;

    }

    private Map<String, List<Catelog2Vo>> getDataFromDB() {
        String catelogJSON = stringRedisTemplate.opsForValue().get("catelogJSON");
        if (!StringUtils.isEmpty(catelogJSON)) {
            Map<String, List<Catelog2Vo>> returnValue = JSON.parseObject(catelogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
            });
            return returnValue;
        }
        log.error("查询了数据库。。。");
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        // 1、查出所有一级分类
        List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);
        // 2、封装数据
        Map<String, List<Catelog2Vo>> parent_cid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            // 每一个一级分类，查到这个一级分类的二级分类
            List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());
            // 封装上面的结果
            List<Catelog2Vo> catelog2Vos = null;
            if (categoryEntities != null) {
                catelog2Vos = categoryEntities.stream().map(item -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, item.getCatId().toString(), item.getName());
                    // TODO 找当前二级分类的三级分类封装成vo
                    List<CategoryEntity> categoryEntityList3 = getParent_cid(selectList, item.getCatId());
                    List<Catelog2Vo.Category3Vo> category3VoList = null;
                    if (categoryEntityList3 != null) {
                        category3VoList = categoryEntityList3.stream().map(item3 -> {
                            Catelog2Vo.Category3Vo category3Vo = new Catelog2Vo.Category3Vo(catelog2Vo.getId(), item3.getCatId().toString(), item3.getName());
                            return category3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(category3VoList);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2Vos;
        }));
//        stringRedisTemplate.opsForValue().set("catelogJSON", JSON.toJSONString(parent_cid), 1, TimeUnit.DAYS);
        return parent_cid;
    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList, Long parent_cid) {
        return selectList.stream().filter(item -> item.getParentCid() == parent_cid).collect(Collectors.toList());
//        return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getParentCid()));
    }

    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream().filter((categoryEntity) -> {
            return categoryEntity.getParentCid() == root.getCatId();
        }).map((entity -> {
            // 1.找到子菜单
            entity.setChildren(getChildren(entity, all));
            return entity;
        })).sorted((entity1, entity2) -> {
            // 2。菜单的排序
            return (entity1.getSort() == null ? 0 : entity1.getSort()) - (entity2.getSort() == null ? 0 : entity2.getSort());
        }).collect(Collectors.toList());
        return children;
    }

}